package com.qf.readredistodb.producer;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.readredistodb.dbvote.entity.Vote;
import com.qf.readredistodb.util.Constants;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class VoteLogProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 创建定时任务
     * 查询redis中数据是否是十的倍数
     *      满足 则查询redis 中保存的上次查询下标
     *              将最后十条数据发送RibbtMQ消息到交换机
     *              将最后下标写入redis中 覆盖原有数据
     *      不满足则 跳过
     *
     *
     *
     */
    @Scheduled(cron = "0/10 * * * * ? ")
    private void sendVoteLog() throws JsonProcessingException {

        Long size = redisTemplate.opsForList().size(Constants.VOTE_DETAIL_LIST);

        Object ob = redisTemplate.opsForValue().get(Constants.VOTE_LEST_SELECT_INDEX);
        long o = 0;

        if (ob != null) {
            o = Long.parseLong(ob.toString());
        }


        if (size % Constants.REDIS_TO_DB_NUMS == 0&& size > o) {

            List<Vote> list = redisTemplate.opsForList().range(Constants.VOTE_DETAIL_LIST, o, o+Constants.REDIS_TO_DB_NUMS-1);

            //转换为Json字符串并发送给交换机
            ObjectMapper objectMapper = new ObjectMapper();
            String s = objectMapper.writeValueAsString(list);

            rabbitTemplate.convertAndSend("topic_logs","asd.vote.message",s);

            redisTemplate.opsForValue().set(Constants.VOTE_LEST_SELECT_INDEX, o + Constants.REDIS_TO_DB_NUMS);

        }
    }





}
